<template>
  <!-- 发票信息弹窗 -->
  <div>
    <el-dialog
      :title="dialogParam.title"
      v-model="dialogParam.open"
      :width="dialogParam.width"
      @close="cancelFn"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="110px"
        :disabled="formDisabled"
      >
        <el-row :gutter="40">
          <el-col :span="formData.invoiceType == '6' ? 6 : 12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select
                class="w-full"
                v-model="formData.invoiceType"
                placeholder="请选择发票类型"
                @change="
                  () => {
                    formData.headerType = 1
                  }
                "
              >
                <el-option
                  v-for="item in invoice_manage_type_order"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <!-- <el-radio-group
                v-model="formData.invoiceType"
                @change="
                  () => {
                    formData.headerType = 1
                  }
                "
              >
                <el-radio-button
                  v-for="(item, index) in invoice_manage_type_order"
                  :label="item.value"
                  :key="index"
                  >{{ item.label }}
                </el-radio-button>
              </el-radio-group> -->
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.invoiceType == '6'">
            <el-form-item label="抬头类型" prop="headerType">
              <el-radio-group
                v-model="formData.headerType"
                @change="clearValidate"
              >
                <el-radio-button
                  v-for="(item, index) in invoice_header"
                  :label="item.value"
                  :key="index"
                  >{{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="formData.invoiceMethod == '1' ? 12 : 7">
            <el-form-item label="开票方式" prop="invoiceMethod">
              <el-select
                class="w-full"
                v-model="formData.invoiceMethod"
                placeholder="请选择开票方式"
              >
                <el-option
                  v-for="item in invoice_method"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" v-if="formData.invoiceMethod == '2'">
            <el-form-item label="" prop="deduction" label-width="0">
              <template #label="{ label }">
                <div class="w-full">{{ label }}</div>
              </template>
              <el-input v-model="formData.deduction" placeholder="扣除额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票抬头" prop="invoiceTitle">
              <el-input
                v-model="formData.invoiceTitle"
                placeholder="开票抬头"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="社会信用代码"
              :prop="formData.headerType == '1' ? 'socialCreditCode' : ''"
            >
              <el-input
                v-model="formData.socialCreditCode"
                placeholder="社会信用代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收手机" prop="invoicePhone">
              <el-input
                v-model="formData.invoicePhone"
                placeholder="接收手机"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收邮箱" prop="receiveEmail">
              <el-input
                v-model="formData.receiveEmail"
                placeholder="接收邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="企业电话" prop="taxPhone">
              <el-input v-model="formData.taxPhone" placeholder="企业电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="企业地址" prop="invoicePlace">
              <el-input
                v-model="formData.invoicePlace"
                placeholder="企业地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="开户银行" prop="invoiceBank">
              <el-input
                v-model="formData.invoiceBank"
                placeholder="填写开户银行"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="银行账号" prop="invoiceBankAccount">
              <el-input
                v-model="formData.invoiceBankAccount"
                placeholder="银行账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票备注" prop="invoiceRemark">
              <el-input
                v-model="formData.invoiceRemark"
                placeholder="发票备注"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <avue-crud
              ref="crudProduct"
              :option="crudOptionProduct"
              :data="formData.productList"
              class="hide-required-asterisk"
            >
              <!-- :row-class-name="rowClassName" -->
              <!-- <template #menu-left>
              <el-button type="primary" icon="Plus" @click="addProduct"
                >添加产品</el-button
              >
            </template> -->
              <!-- <template #serviceDateArr-form="{ row }">
                <el-date-picker
                  v-model="row.serviceDateArr"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="服务开始时间"
                  end-placeholder="服务结束时间"
                  :size="size"
                />
              </template> -->
              <template #menu="{ row }">
                <el-switch
                  v-model="row.openInvoice"
                  @change="changeSwitch(row)"
                />
                <!-- <el-button
                  plain
                  icon="Delete"
                  link
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                > -->
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <slot name="bottomBtn"></slot>
          <!-- <el-button @click="cancelUpload">取消</el-button> -->
          <el-button
            type="primary"
            v-loading="dialogParam.btnLoading"
            :disabled="dialogParam.btnLoading"
            @click="saveInvoice"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="InvoiceDia">
import { reactive, toRefs, ref } from 'vue'
import { validatePhoneNot, maxDecimals } from '@/utils/validate'
import { myToFixed } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import { parseTime } from '@/utils/ruoyi'
import {
  crudOption, // 子表公用配置
  invoice_manage_type_order, //订单发票类型
  measurement_unit, //产品单位
  invoice_method, //开票方式
  invoice_header //抬头类型
} from '@/hooks/dict/order'

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {
        formData: {},
        formRules: {},
        btnLoading: true
      }
    }
  }
})

const dialogParam = ref({
  open: props.dialogParam.open,
  title: '发票信息',
  width: '1100px',
  btnLoading: props.dialogParam.btnLoading
})
const formData = ref({
  invoiceType: '6', //发票类型，默认数电普通电子发票
  headerType: '1', //抬头类型，默认企业
  invoiceMethod: '1', //开票方式
  deduction: '' //扣除额
})
const formRules = ref({
  invoiceTitle: [
    {
      required: true,
      message: '请输入开票抬头',
      trigger: 'blur'
    }
  ],
  socialCreditCode: [
    {
      required: false,
      message: '请输入社会信用代码',
      trigger: 'blur'
    }
  ],
  invoicePhone: [
    {
      validator: validatePhoneNot
    }
  ],
  receiveEmail: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  deduction: [
    {
      required: true,
      message: '请输入扣除额',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        maxDecimals(rule, value, callback, 2)
      }
    }
  ]
})
const formDisabled = ref(false)

const crudOptionProduct = ref({
  ...crudOption,
  menu: false,
  menuTitle: '是否开票',
  header: false,
  column: [
    // {
    //   label: '是否开票',
    //   prop: 'openInvoice',
    //   type: 'switch',
    //   width: '80',
    //   fixed: true,
    //   cell: true,
    //   change: val => {
    //     const { value, row } = val
    //   }
    // },
    {
      label: '开票名称',
      prop: 'invoiceName',
      cell: true,
      minWidth: '150',
      rules: [
        {
          required: true,
          message: '请输入开票名称',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '开票规格型号',
      width: '150',
      prop: 'invoiceSpecification',
      cell: true
    },
    {
      label: '单位',
      prop: 'unit',
      type: 'select',
      width: '90',
      clearable: false,
      dicData: measurement_unit,
      cell: true
    },
    {
      label: '实际售价',
      prop: 'actualPrice',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '80',
      controls: false,
      cell: false
    },
    // {
    //   label: '数量(已开)',
    //   prop: 'openedNum',
    //   type: 'number',
    //   // min: 0, //由于是红蓝单所以可负数
    //   class: 'w-full',
    //   controls: false,
    //   // precision: 0,
    //   width: '100',
    //   cell: false
    // },
    {
      label: '数量',
      prop: 'invoiceNum',
      type: 'input',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '100',
      rules: [
        {
          required: true,
          message: '请输入数量',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            maxDecimals(rule, value, callback, 6)
          }
        }
      ],
      blur: val => {
        const { value, row } = val
        if (0 < value && value <= row.num - row.openedNum) {
          row.unOpenedPrice = myToFixed(row.actualPrice * row.invoiceNum, 6)
        } else {
          proxy.$message.error('数量不能小于0或大于剩余数量')
          row.invoiceNum = ''
        }
      },
      cell: false
    },
    // {
    //   label: '总数量',
    //   prop: 'num',
    //   type: 'number',
    //   // min: 0, //由于是红蓝单所以可负数
    //   class: 'w-full',
    //   controls: false,
    //   // precision: 0,
    //   width: '80',
    //   cell: false
    // },
    // {
    //   label: '金额(已开)',
    //   prop: 'openedPrice',
    //   type: 'number',
    //   min: 0,
    //   class: 'w-full',
    //   width: '100',
    //   controls: false,
    //   cell: false
    // },
    // {
    //   label: '金额',
    //   prop: 'unOpenedPrice',
    //   type: 'number',
    //   min: 0,
    //   class: 'w-full',
    //   width: '100',
    //   controls: false,
    //   cell: false
    // },
    {
      label: '开票金额(元)',
      width: '100',
      prop: 'invoiceTotalPrice',
      cell: false
    },
    {
      label: '税率',
      width: '100',
      prop: 'taxRate',
      cell: false
    }
  ]
})
watch(
  () => props.dialogParam,
  async val => {
    formData.value = {
      ...val.formData,
      invoiceType: val.formData?.invoiceType ? val.formData.invoiceType : '1', //发票类型，默认数电普通电子发票
      headerType: val.formData?.headerType ? val.formData.headerType : '1', //抬头类型，默认企业
      invoiceMethod: val.formData?.invoiceMethod
        ? val.formData.invoiceMethod
        : '1', //开票方式
      invoiceRemark: val.formData?.invoiceRemark,
      productList:
        val.formData?.productList && val.formData?.productList.length > 0
          ? val.formData.productList.map(item => {
              return {
                ...item,
                openInvoice: true, //item.invoiceNum && item.invoiceNum != 0,
                $cellEdit: true //item.invoiceNum && item.invoiceNum != 0
              }
            })
          : []
    }
    formRules.value = val.formRules ? val.formRules : formRules.value
    dialogParam.value.open = val.open
    dialogParam.value.btnLoading = val?.btnLoading

    // 物料编号为H00040000001541_7501时带入服务时间
    if (
      formData.value.productList &&
      formData.value.productList.length > 0 &&
      formData.value.productList.some(e => e.number == 'H00040000001541_7501')
    ) {
      let productList = formData.value.productList.filter(
        item => item.number == 'H00040000001541_7501'
      )
      let serverData = []
      productList.forEach(item => {
        if (item.startDate) {
          serverData.push(
            `服务期限:${parseTime(
              item.startDate,
              '{y}年{m}月{d}日'
            )}至${parseTime(item.endDate, '{y}年{m}月{d}日')}`
          )
        }
      })
      if (formData.value.invoiceRemark) {
        formData.value.invoiceRemark += `;${serverData.toString()}`
      } else {
        formData.value.invoiceRemark = serverData.toString()
      }
    }
  },
  {
    // flush: 'post'
    immediate: true,
    deep: true
  }
)

const changeSwitch = row => {
  row.$cellEdit = row.openInvoice
  if (row.openInvoice && row.invoiceNum && row.invoiceNum == 0) {
    row.invoiceNum = ''
  }
}

const emit = defineEmits(['ok', 'close'])
const saveInvoice = () => {
  proxy.$refs.form.validate(async (valid, msg) => {
    // 产品信息信息校验
    let errMsg = []
    let productList = formData.value.productList.filter(e => e.openInvoice)
    let err = await proxy.$refs.crudProduct.validateCellForm()
    if (err) {
      errMsg.push(`产品信息---${err[Object.keys(err)[0]][0].message}`)
    }
    if (msg) errMsg.unshift(`${msg[Object.keys(msg)[0]][0].message}`)
    if (productList.length > 1 && formData.value.invoiceMethod == '2') {
      errMsg.push('差额开票时，产品信息只能选择一个产品!')
    }
    if (valid && errMsg.length == 0) {
      // cancelFn()
      // console.log('formData==>', formData.value)
      emit('ok', formData.value)
    } else {
      if (errMsg.length > 0) proxy.$modal.msgError(errMsg[0])
    }
  })
}

const rowClassName = ({ row, rowIndex }) => {
  // console.log('row,rowIndex==>', row, rowIndex)
  return row.openInvoice ? '' : 'unInvoice'
}

const clearValidate = () => {
  proxy.$refs.form.clearValidate()
}

// 取消
function cancelFn() {
  emit('close', false)
}
</script>
<style lang="scss" scoped>
.hide-required-asterisk {
  :deep(.unInvoice) {
    @apply bg-slate-200;
  }
}
</style>
